package com.itheima.web.controller.store;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.core.BaseServlet;
import com.itheima.dao.store.CourseDao;
import com.itheima.domain.store.Course;
import com.itheima.service.store.CourseService;
import com.itheima.service.store.impl.CourseServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/store/course/*")
public class CourseServlet extends BaseServlet {
    private CourseService courseService = new CourseServiceImpl();

    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*1.获取表单数据*/

        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if(StringUtil.isEmpty(pageNum)){
            pageNum="1";
        }
        if(StringUtil.isEmpty(pageSize)){
            pageSize="10";
        }
        /*2.调用Service*/
        PageInfo<Course> pageInfo = courseService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        /*3.回显数据*/
        request.setAttribute("page",pageInfo);
        return "WEB-INF/pages/store/course/list.jsp";
    }

    /**
     * 跳转到新建add.jsp页面
     */
    public String toAdd(HttpServletRequest request, HttpServletResponse response)throws Exception{
    return "WEB-INF/pages/store/course/add.jsp";

    }

    /**
     * 保存，保存完毕后跳转到列表页面
     */
    public String save(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Course course = BeanUtil.fillBean(request, Course.class);
        courseService.save(course);

        return "store/course/list";
    }

    /**
     * 根据ID回显数据
     */
    public String toEdit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        /*查询当前部门信息*/
        Course byId = courseService.findById(id);
        request.setAttribute("course",byId);

        return "WEB-INF/pages/store/course/update.jsp";
    }

    /**
     * 更新数据，更新完毕后跳转到列表页面
     */
    public String edit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Course course = BeanUtil.fillBean(request, Course.class);
        courseService.update(course);
        return "store/course/list";
    }

    /**
     * 删除，删除完毕跳转到列表页面
     */
    public String delete(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String[] ids = request.getParameterValues("id");
        courseService.deleteById(ids);
        return "store/course/list";
    }
}
